
from mahbo.information.database.utility.dbinterface import DatabaseInterface

from minings.utility.utility import (RUN,DatasetTools,)
from minings.factory.datapreprocess import DataPrePackage
from copy import deepcopy
import os,numpy,orange,orngMySQL,MySQLdb,xlwt,xlrd,cPickle,string
from xlutils.copy import copy
import psyco
psyco.full() #Speeding Up Python


class SITES(object):
    
    def __init__(self,**kwargs):
        self.Site       = None
        self.Method     = None
        self.Class_X    = None
        self.Class_1    = None
        self.Class_2    = None
        self.Class_3    = None
        self.__dict__.update(kwargs)
        self.built      = True
        
        
class LINKED(object):
    
    def __init__(self,**kwargs):
        self.Capillary      = None
        self.Disease_Status = None
        self.Project        = None
        self.Sex            = None
        self.Age            = None
        self.__dict__.update(kwargs)
        self.built          = True


class GutPackage(DataPrePackage):
    
    def __init__(self,**kwargs):
        #Arbitrary properties
        self.Method         = None
        self.Class_X        = None
        self.Class_2        = None
        self.Class_3        = None
        self.__dict__.update(kwargs)
        DataPrePackage.__init__(self,**kwargs)


class INFO(object):
    
    def __init__(self,**kwargs):
        self.fullname       = ""
        self.dataoption     = 1 #0:Whole classes except self.permremovelist,1:fixclass,2:both,3:all duals
        self.permremovelist = [""]
        self.fixedcls       = ""
        self.matrix         = [ [], [] ]
        self.run            = None
        #Arbitrary properties
        self.Method         = None
        self.Class_X        = None
        self.Class_2        = None
        self.Class_3        = None
        self.Length         = None
        self.__dict__.update(kwargs)


class GUTLHPCRSPEC(DatabaseInterface):
    
    def __init__(self,**kwargs):        
        self.mainfullname               = 'gut'
        self.table_gut                  = 'gut'
        self.gut_colon2                 = 'gut_colon2'
        self.gut_colon3                 = 'gut_colon3'
        self.colon_both                 = [self.gut_colon2]
        self.maindataoption             = 1 #0:Whole classes except self.permremovelist,1:fixclass,2:both,3:all duals
        self.mainpermremovelist         = ['Polyp','Diverticulitis','Normal Pouch','Pouchitis','Alcoholic', 'ALD', 'Non ALD']
        self.mainfixedcls               = 'Healthy Control'
        self.mainrun                    = RUN()
        #xcel file for writing
        self.__dict__.update(kwargs)
        DatabaseInterface.__init__(self,self.mainfullname)       
        self.t                          = orngMySQL.Connect('localhost','root','dudesweet',self.mainfullname)
        #Start
        self.getRawdataMySQL()
        
    def getRawdataMySQL(self):
#        self.doAll()
        #Get a list of table names
        self.RA.query("""SELECT * FROM %s""" % (self.RA.tab_L.tablename))
        self.doAll_bool = False #Indicate to do everything anew again or not
        tempraw         = []
        row             = self.RA.cursor.fetchall()
        if row not in (None,()): #I have to make sure table "gut" exists
            self.rawdata    = {}
            #Check whether I have everything ready to construct datapackage
            for i in row:
                dataname    = i[self.RA.tab_L.name]
                info        = cPickle.loads(i[self.RA.tab_L.info])
                tempraw.append((dataname,info))   
#                tempraw.append((dataname,None))              
                try:
                    #Check if all tables exist or not
                    self.RA.query("""DESC %s""" % (dataname))
                except (MySQLdb.ProgrammingError,),e:
                    if e[0] != 1146:
                        raise MySQLdb.ProgrammingError
                    else:
                        #Catch only 1146,error elsewhere got dumped
                        #if only one dataname does not exist
                        self.doAll_bool = True
                        break
        else:
            self.doAll_bool = True
        if self.doAll_bool:
#            print 'doAll is True'
            #if signal doAll_bool -> True,do everything again
            self.doAll()
        else:
            print 'doall false'
            self.rawdata = {}
            for i in tempraw:
                #tempraw -> [(dataname,INFO instance),]
                if i[0] not in ('gut_Entire_Colon2','gut_Endo_Ileum','gut_Endo_Colon2','gut_Endo_Sigmoid','gut_Endo_Lumen',): 
                    continue
                print "dataname: %s" % i[0]
                tempdata            = self.t.query("""SELECT * FROM %s""" % i[0])
                self.rawdata[i[0]]  = GutPackage(fullname  = i[0]          ,data       = tempdata      ,dataoption = i[1].dataoption   ,permremovelist = i[1].permremovelist   ,
                                                 fixedcls  = i[1].fixedcls ,matrix     = i[1].matrix   ,run        = i[1].run          ,Method         = i[1].Method           ,
                                                 Class_X   = i[1].Class_X  ,Class_2    = i[1].Class_2  ,Class_3    = i[1].Class_3      ,Length         = i[1].Length   ) 
        
    def doAll(self):
        ##########################
        ###Start Gathering Data###
        ##########################
        self.rawdata        = {}#{'gut_1':DataPackage instance, .. }
        self.keyRank        = []
        self.getAlldata()
                
    def getAlldata(self):
        print 'getAlldata'
        #Get Entire_Colon2 with
        #Method     = Endoscopic
        #Class X    = Ileum, Ascending_Colon, Transverse_Colon, Sigmoid with Class_2 and Class_3 has having values != ""
        #             and Lumen, Stool 
#        d     = self.t.query("""SELECT * FROM %s 
#                                           """ % ('gut_colon2' ))
#        print len(d)
        xname               = "gut_Entire_Colon2"
        d_entire_colon2     = self.t.query("""SELECT * FROM %s WHERE ( ( (%s in ("%s","%s","%s","%s")) and (%s!="%s" and %s!="%s") ) or (%s in ("%s")) )
                                                                     and  %s="%s"
                                           """ % (self.table_gut,   "m$Class_X"     ,"Ileum"    ,"Ascending_Colon"  ,"Transverse_Colon" ,"Sigmoid"      ,
                                                                    "m$Class_2"     ,""         ,"m$Class_3"        ,""                 ,"m$Class_X"    ,
                                                                    "Lumen"         ,"m$Method" ,"Endoscopic"       ))
        self.rawdata[xname] = GutPackage(fullname          = xname                     ,data       = d_entire_colon2       ,dataoption = self.maindataoption   ,
                                         permremovelist    = self.mainpermremovelist   ,fixedcls   = self.mainfixedcls     ,run        = self.mainrun          ,
                                         Method            = "Endoscopic"              ,Class_X    = None                  ,Class_2    = None                  ,
                                         Class_3           = None                      ,Length     = len(d_entire_colon2)     )
        self.keyRank.append(xname)
        #Get Endo_Ileum with
        #Method     = Endoscopic
        #Class_X    = Ileum and Class_2 and Class_3 has having values != ""
        xname               = "gut_Endo_Ileum"
        d_endo_ileum        = self.t.query("""SELECT * FROM %s WHERE (%s in ("%s")) and (%s="%s" and %s!="%s" and %s!="%s")
                                           """ % (self.table_gut,   "m$Class_X"     ,"Ileum"    ,"m$Method"         ,"Endoscopic"   ,
                                                                    "m$Class_2"     ,""         ,"m$Class_3"        ,""     ) )
        #Find method and class_x
        self.rawdata[xname] = GutPackage(fullname          = xname                     ,data       = d_endo_ileum          ,dataoption = self.maindataoption   ,
                                         permremovelist    = self.mainpermremovelist   ,fixedcls   = self.mainfixedcls     ,run        = self.mainrun          ,
                                         Method            = "Endoscopic"              ,Class_X    = "Ileum"               ,Class_2    = None                  ,
                                         Class_3           = None                      ,Length     = len(d_endo_ileum)     )
        self.keyRank.append(xname)
        #Get Endo_Colon2 (Ascending_Colon + Transverse_Colon) with Class_2 and Class_3 has having values != ""
        xname               = "gut_Endo_Colon2"
        d_endo_colon2       = self.t.query("""SELECT * FROM %s WHERE (%s in ("%s","%s")) and (%s="%s" and %s!="%s" and %s!="%s")
                                           """ % (self.table_gut,   "m$Class_X"     ,"Ascending_Colon"  ,"Transverse_Colon"     ,"m$Method"     ,"Endoscopic"   ,
                                                                    "m$Class_2"     ,""                 ,"m$Class_3"            ,""     ) )
        #Find method and class_x
        self.rawdata[xname] = GutPackage(fullname          = xname                     ,data       = d_endo_colon2         ,dataoption = self.maindataoption   ,
                                         permremovelist    = self.mainpermremovelist   ,fixedcls   = self.mainfixedcls     ,run        = self.mainrun          ,
                                         Method            = "Endoscopic"              ,Class_X    = None                  ,Class_2    = None                  ,
                                         Class_3           = None                      ,Length     = len(d_endo_colon2)     )
        self.keyRank.append(xname)
        #Get Endo_Sigmoid with Class_2 and Class_3 has having values != ""
        xname               = "gut_Endo_Sigmoid"
        d_endo_sigmoid      = self.t.query("""SELECT * FROM %s WHERE (%s in ("%s")) and (%s="%s" and %s!="%s" and %s!="%s")
                                           """ % (self.table_gut,   "m$Class_X"     ,"Sigmoid"      ,"m$Method"     ,"Endoscopic"   ,
                                                                    "m$Class_2"     ,""             ,"m$Class_3"    ,""     ) )
        #Find method and class_x
        self.rawdata[xname] = GutPackage(fullname          = xname                     ,data       = d_endo_sigmoid        ,dataoption = self.maindataoption   ,
                                         permremovelist    = self.mainpermremovelist   ,fixedcls   = self.mainfixedcls     ,run        = self.mainrun          ,
                                         Method            = "Endoscopic"              ,Class_X    = None                  ,Class_2    = None                  ,
                                         Class_3           = None                      ,Length     = len(d_endo_sigmoid)   )
        self.keyRank.append(xname)
        #Get Endo_Lumen
        xname                   = "gut_Endo_Lumen"
        d_endo_lumen            = self.t.query("""SELECT * FROM %s WHERE %s="%s" and %s="%s"
                                               """ % (self.table_gut,    "m$Method"      ,"Endoscopic"       ,"m$Class_X"    ,"Lumen" ) )
        self.rawdata[xname]     = GutPackage(fullname          = xname                     ,data       = d_endo_lumen          ,dataoption = self.maindataoption   ,
                                             permremovelist    = self.mainpermremovelist   ,fixedcls   = self.mainfixedcls     ,run        = self.mainrun          ,
                                             Method            = "Endoscopic"              ,Class_X    = "Lumen"               ,Class_2    = None                  ,
                                             Class_3           = None                      ,Length     = len(d_endo_lumen)     )
        self.keyRank.append(xname)
        #Record Data
        for i in self.keyRank:
            #Assign name
            fullname                = i
            self.rawdata[i].data    = DatasetTools.finalBrush(self.rawdata[i].data)
            #Construct INFO instance
            info_obj    = INFO(fullname = self.rawdata[i].fullname  ,dataoption = self.rawdata[i].dataoption    ,permremovelist = self.rawdata[i].permremovelist    ,
                               fixedcls = self.rawdata[i].fixedcls  ,matrix     = self.rawdata[i].matrix        ,run            = self.rawdata[i].run               ,
                               Method   = self.rawdata[i].Method    ,
                               Class_X  = self.rawdata[i].Class_X   ,Class_2    = self.rawdata[i].Class_2       ,Class_3        = self.rawdata[i].Class_3           ,
                               Length   = self.rawdata[i].Length )
            info_string = MySQLdb.escape_string(cPickle.dumps(info_obj,2))
            self.RA.query("""insert into %s values  ("%s","%s")
                          """ % ( self.RA.tab_L.tablename, fullname, info_string ) )
#        print self.keyRank
#        print '###########'
#        print self.rawdata.keys()
            


